package com.yljk.yljkproject.ui;

import static com.yilijk.base.utils.DevicesUtils.DEVICES_UUID;
import static com.yilijk.base.utils.DevicesUtils.getUUID;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.mobstat.StatService;
import com.yilijk.base.AppBase;
import com.yilijk.base.constants.UserInfo;
import com.yilijk.base.network.config.BaseConfig;
import com.yilijk.base.network.config.BaseUrl;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.NetAttestationUtils;
import com.yilijk.base.network.https.interceptor.NetWorkUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yljk.servicemanager.constants.ConfigApi;
import com.yljk.servicemanager.constants.RouterApi;
import com.yljk.servicemanager.oldbase.ModuleBaseActivity;
import com.yljk.servicemanager.interfaceapi.NetWorkCallBack;
import com.yljk.yljkproject.MyApplication;
import com.yljk.yljkproject.R;

import crossoverone.statuslib.StatusUtil;

@Route(path = RouterApi.WelActivity)
public class WelActivity extends ModuleBaseActivity {
    private ImageView loginicon;
    private Animation alphaAnimation = null;
    //保存到SDcard的路径
    private String saveFilePath = "/sdcard/updataApk/";
    //下载完成后的文件名
    private String saveFileName = saveFilePath + "apkName.zip";
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getBooleanExtra(ConfigApi.finishWel, false)) {
                ALog.d("收到广播", "finishWel");
                finish();
            }
        }
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                //安装APK
                Toast.makeText(WelActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
//                installApl();
            }
            if (msg.what == 2) {
                //更新进度
//                nowSize.setText(msg.arg1+"");
//                dialogProgress.setProgress(msg.arg1);
//                allSize.setText(msg.arg2+"");
//                dialogProgress.setMax(msg.arg2);
            }
            if (msg.what == 2) {

            }
        }
    };

    @Override
    public int bondLayout() {
        return R.layout.activity_wel;
    }

    @Override
    public void initView() {

        ALog.e("oakkkk","get salt thread" + Thread.currentThread().getName() + " ==> " + Thread.currentThread().getId());
//        NetAttestationUtils.getInstance().setSALT("");
//        NetAttestationUtils.getInstance().requestInterfaceToGetSalt(this, false, new NetAttestationUtils.SaltListener() {
//            @Override
//            public void getSuccess(String s) {
//                ALog.e("oakkkk","get salt success: " + s );
//            }
//
//            @Override
//            public void getFailure(String s) {
//                ALog.e("oakkkk","get salt fail: " + s );
//
//            }
//        });
        // 下载安装打开后 后台重启
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
        }
        // setSendLogStrategy已经@deprecated，建议使用新的start接口
        // 如果没有页面和自定义事件统计埋点，此代码一定要设置，否则无法完成统计
        // 进程第一次执行此代码，会导致发送上次缓存的统计数据；若无上次缓存数据，则发送空启动日志
        // 由于多进程等可能造成Application多次执行，建议此代码不要埋点在Application中，否则可能造成启动次数偏高
        // 建议此代码埋点在统计路径触发的第一个页面中，若可能存在多个则建议都埋点
        if (MyApplication.getMyApplication().isUserAgreeChecked()) {
            StatService.start(this);
        }
        if (Build.VERSION.SDK_INT >= 21) {
            StatusUtil.setUseStatusBarColor(this, Color.WHITE);
            StatusUtil.setSystemStatus(this, false, false);
        }
        //注册广播接收器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BaseConfig.Receiver.BroadcastReceiver);
        registerReceiver(broadcastReceiver, intentFilter);
        loginicon = findViewById(R.id.loginicon);
        alphaAnimation = AnimationUtils.loadAnimation(this,
                R.anim.showview);
        alphaAnimation.setFillEnabled(true);//启动Fill保持
        alphaAnimation.setFillAfter(true);//设置动画的最后一帧是保留在view上的
        loginicon.setAnimation(alphaAnimation);


    }

    @Override
    protected void onRestart() {
        super.onRestart();
        String token = SharedPreferencesUtils.getInstance().getString(UserInfo.token, null);
        String mobile = SharedPreferencesUtils.getInstance().getString(UserInfo.mobile, null);
        String hasPassword = SharedPreferencesUtils.getInstance().getString(UserInfo.hasPassword, "");
        if (token != null && mobile != null && mobile.length() == 11 && !hasPassword.equals("0") && !hasPassword.equals("")) {
            ARouter.getInstance().build(RouterApi.MAIN_ACTIVITY).navigation();
        } else {
            ARouter.getInstance().build(RouterApi.CenterActivity).navigation();
//            ReactUtils.INSTANCE.push(WelActivity.this,ReactApi.LOGIN_DOCTORBUNDLE,ReactApi.Index);
        }
        finish();
    }


    @Override
    public void initData() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }

    @Override
    public void initEvent() {
        alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                //判断是否需要更新
//                isRefresh();

                String token = SharedPreferencesUtils.getInstance().getString(UserInfo.token, null);
                String mobile = SharedPreferencesUtils.getInstance().getString(UserInfo.mobile, null);
                String hasPassword = SharedPreferencesUtils.getInstance().getString(UserInfo.hasPassword, "");
                if (token != null && mobile != null && mobile.length() == 11 && !hasPassword.equals("0") && !hasPassword.equals("")) {
                    ARouter.getInstance().build(RouterApi.MAIN_ACTIVITY).navigation();
                } else {
                    ARouter.getInstance().build(RouterApi.CenterActivity).navigation();
//            ReactUtils.INSTANCE.push(WelActivity.this,ReactApi.LOGIN_DOCTORBUNDLE,ReactApi.Index);
                }

                finish();


            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void isRefresh() {
        //获取当前版本号
        String version = DevicesUtils.getVersionName(); // 1.0.0
        //从接口获取最新的version
        String new_version = "1.0.1";
        if (!version.equals(new_version)) {
            boolean isForceRefresh = true;
            //需要更新 判断是否强制跟新
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.refreshTitle);
            builder.setMessage(R.string.refreshMessage);
            builder.setPositiveButton(R.string.refresh, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //开始下载更新
                    HttpUtils.downloadFile("https://imageserver.yilijk.com/mobile/3/zip", saveFilePath, saveFileName, new HttpCallBack<String>() {
                        @Override
                        public void onSuccess(String result, int code) {

                        }

                        @Override
                        public void onFailure(String failureMsg, int statusCode) {

                        }
                    });
                    handler.sendEmptyMessage(1);
//                    downloadApl("https://imageserver.yilijk.com/mobile/3/zip");
                }
            });
            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (!isForceRefresh) {
                        System.exit(0);
                    } else {
                    }
                }
            });
            builder.setCancelable(false);
            builder.create();
            //显示更新
            builder.show();
            // 放入服务器的apk地址
        } else {
            ARouter.getInstance().build(RouterApi.MAIN_ACTIVITY).navigation();
        }
    }

    //在欢迎页面屏蔽BACK键
    @Override
    public boolean onKeyDown(int KeyCode, KeyEvent event) {
        if (KeyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }
        return false;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

}